package trade.axht.java_feature.lambda;

import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;

/**
 * 描述:
 * Java8内置四大核心函数式接口
 *
 * @outhor Administrator
 * @create 2017-11-13 23:57
 */
public class InnerClass {

    /**
     * Consumer<T> 消费型接口
     */
    @Test
    public void testConsume(){
        consumer((m)-> System.out.println("你好,"+m));
    }
    public void consumer(Consumer<String> consumer){
        consumer.accept("Lambda!");
    }

    /**
     * Supplier<T> 供给型接口
     */
    @Test
    public void testSupplier(){
        List<Integer> numList=getNumList(10,()->(int)(Math.random()*1000));
        numList.forEach(System.out::println);
    }
    public List<Integer> getNumList(int num, Supplier<Integer> supplier){
        List<Integer> numList=new ArrayList<>();
        for(int i=0;i<num;i++){
            numList.add(supplier.get());
        }
        return numList;
    }


    /**
     * Function<T,R> 函数型接口
     */
    @Test
    public void testFunction(){
        String newStr=handleStr("aaaaa",(str)->str.toUpperCase());
        System.out.println(newStr);
    }

    public String handleStr(String str, Function<String,String> fn){
        return fn.apply(str);
    }

    /**
     * Predicate<T>断言型接口
     */
    @Test
    public void testPredicate(){
        List<String> stringList=predicate(Arrays.asList("Java","Python","PHP"),(s)->s.length()>5);
        stringList.forEach(System.out::println);
    }

    public List<String> predicate(List<String> list, Predicate<String> predicate){
        List<String> stringList=new ArrayList<>();
        list.forEach(s -> {
            if(predicate.test(s)){
                stringList.add(s);
            }
        });
        return stringList;
    }


}
